package cz.fimuni.pa165.backendderby.dao;

import cz.fimuni.pa165.backendderby.entities.Employee;
import cz.fimuni.pa165.backendderby.entities.Reservation;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Andrej Hraško
 */
@Repository
public class ReservationDAOImpl implements ReservationDAO {
    
    @PersistenceContext
    private EntityManager em;
    
    @Override
    public void create(Reservation reservation) {
        if (reservation == null) {
            throw new IllegalArgumentException("Argument is NULL");
        }
        
        List<Reservation> list = getAllReservations();
        Reservation temp;
        for (int i = 0; i < list.size(); i++) {
            temp=list.get(i);
            if (reservation.isSame(temp)) {
                throw new IllegalArgumentException("Car is already reserved to that date!");
            }
        }
        
        em.persist(reservation);

    }
    
    @Override
    public boolean update(Reservation reservation) {
        if (reservation != null) {
            if (em.find(Employee.class, reservation.getId()) == null) {
                return false;
            }
            em.persist(em.merge(reservation));
            return true;
        }
        return false;
    }
    
    @Override
    public void remove(Reservation reservation) {
        if (reservation != null) {
            Reservation temp = em.find(Reservation.class, reservation.getId());
            if (temp != null) {
                em.remove(temp);
            }
        } else {
            throw new IllegalArgumentException("Argument is NULL");
        }
    }
    
    @Override
    public Reservation getByID(Long id) {
        if (id == null) {
            return null;
        }
        Reservation temp = em.find(Reservation.class, id);
        return temp;
    }
    
    @Override
    public List<Reservation> get(Employee employee) {
        Query q = em.createQuery("SELECT r FROM Reservation r WHERE r.employee= :emp");
        q.setParameter("emp", employee);
        List<Reservation> result = q.getResultList();
        return result;
    }
    
    public List<Reservation> getAllReservations() {
        Query q = em.createQuery("SELECT e FROM Reservation e");
        List<Reservation> result = q.getResultList();
        return result;
    }
}
